import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    # 补充JWT返回值,来满足需求
    return {
        'user_id': user.id,
        'username': user.username,
        'token': token
    }

def get_user_by_account(account):
    """
    用户名或手机号
    :param account:
    :return:
    """
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            # 根据手机号查询
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user

class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """

        :param request:
        :param username:用户名或手机号
        :param password: 密码
        :param kwargs:
        :return:
        """
        user = get_user_by_account(username)

        # 校验密码是否正确
        if user and user.check_password(password):
            return user